package com.gm.tool.utils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * Created by Mouse on 2016/10/23.
 */

public class FileUtil {


    public static void writeToFile(File file, byte[] bytes) {
        FileOutputStream out;
        try {
            out = new FileOutputStream(file);
            out.write(bytes);
            out.flush();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static byte[] readFromFile(File file) {
        byte[] temp = null;
        FileInputStream in;
        try {
            in = new FileInputStream(file);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] bytes = new byte[1024];
            int r = 0;
            while ((r = in.read(bytes)) != -1) {
                baos.write(bytes, 0, r);
            }
            temp = baos.toByteArray();
            baos.close();
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return temp;
    }

    public static int renameFile(String path, String oldname, String newname) {

        if (!oldname.equals(newname)) {//新的文件名和以前文件名不同时,才有必要进行重命名
            File oldfile = new File(path + File.separator + oldname);
            File newfile = new File(path + File.separator + newname);

            if (!oldfile.exists()) {
                return -1;//重命名文件不存在
            }
            if (newfile.exists())//若在该目录下已经有一个文件和新文件名相同，则不允许重命名
                return -2;
            else {
                oldfile.renameTo(newfile);
            }
        } else {
            return -3;
        }

        return 0;
    }


}
